import { useState, useRef, useCallback } from 'react';

interface StreamMessageOptions {
  onMessageReceived?: (content: string, isComplete: boolean) => void;
  onError?: (error: any) => void;
  onStreamStart?: () => void;
  onStreamEnd?: () => void;
}

interface StreamData {
  code?: number;
  data?: {
    answer?: string;
    sessionId?: string;
    [key: string]: any;
  };
  [key: string]: any;
}

export const useStreamMessage = (options: StreamMessageOptions = {}) => {
  const [isStreaming, setIsStreaming] = useState(false);
  const [streamContent, setStreamContent] = useState('');
  const [error, setError] = useState<any>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  // 解析SSE流式响应数据（备用函数，当前未使用但保留以备将来使用）
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const parseStreamChunk = useCallback((chunk: string): StreamData | null => {
    try {
      // 处理SSE格式：每行以 "data:" 开头
      const lines = chunk.split('\n').filter(line => line.trim());
      let latestData: StreamData | null = null;
      
      for (const line of lines) {
        // 跳过非数据行
        if (!line.startsWith('data:')) {
          continue;
        }
        
        // 提取JSON部分
        const jsonStr = line.substring(5).trim(); // 移除 "data:" 前缀
        
        if (!jsonStr) {
          continue;
        }
        
        try {
          const parsed = JSON.parse(jsonStr);
          
          // 检查是否包含answer数据
          if (parsed.data && parsed.data.answer) {
            latestData = parsed;
          }
        } catch (e) {
          console.warn('解析JSON失败:', jsonStr.substring(0, 50) + '...', e);
          continue;
        }
      }
      
      return latestData;
    } catch (error) {
      console.error('解析流式数据失败:', error);
      return null;
    }
  }, []);

  // 发送流式消息
  const sendStreamMessage = useCallback(async (params: {
    authorization: string;
    chatId: string;
    sessionId: string;
    message: string;
  }) => {
    const { message } = params;
    
    if (!message.trim()) return;

    setIsStreaming(true);
    setStreamContent('');
    setError(null);
    options.onStreamStart?.();

    // 创建新的 AbortController
    abortControllerRef.current = new AbortController();

    try {
      const response = await fetch('https://ai.hzailab.cn/v1/conversation/completion', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'IjMzNTQ2ODc2NTM0MDExZjBiZmU5MGUxNjIxNWM4NjI0Ig.aF5wLQ.Vw5fh2bmG9A9SVvFmNwveXGFKG8',
        },
        body: JSON.stringify({
            "conversation_id": "318a616a46a911f0b84616f96a0dee16",
            "messages": [
              {
                "content": "你好！ 我是你的助理，有什么可以帮到你的吗？",
                "id": "9bd30aa9-7b0a-419d-aa40-cb1bfb34e085",
                "role": "assistant"
              },
              {
                "content": "枸杞功效",
                "doc_ids": [],
                "id": "3a17114e-63d5-4092-905a-3bf05d6d1918",
                "role": "user"
              },
              {
                "content": "知识库中未找到您要的答案！",
                "created_at": 1751012105.5583248,
                "id": "3a17114e-63d5-4092-905a-3bf05d6d1918",
                "role": "assistant"
              },
              {
                "id": "05074323-03cc-48bf-abf5-8311db10b65e",
                "content": "实验室着火了怎么办",
                "role": "user",
                "doc_ids": []
              }
            ]
          }),
        signal: abortControllerRef.current.signal,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      let accumulatedContent = '';
      let buffer = ''; // 用于处理跨块的数据
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          console.log('流式响应完成');
          break;
        }

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        
        // 处理缓冲区中的完整行
        const lines = buffer.split('\n');
        buffer = lines.pop() || ''; // 保留最后一个可能不完整的行
        
        // 处理完整的行
        for (const line of lines) {
          if (!line.trim() || !line.startsWith('data:')) {
            continue;
          }
          
          const jsonStr = line.substring(5).trim();
          if (!jsonStr) {
            continue;
          }
          
          try {
            const parsed = JSON.parse(jsonStr);
            console.log('解析到数据:', parsed);
            
            if (parsed.data && parsed.data.answer) {
              const newContent = parsed.data.answer;
              accumulatedContent = newContent; // 使用最新的完整内容
              setStreamContent(newContent);
              
              // 通知回调函数
              options.onMessageReceived?.(newContent, false);
            }
          } catch (e) {
            console.warn('解析JSON失败:', jsonStr, e);
          }
        }
      }

      // 流式传输完成
      options.onMessageReceived?.(accumulatedContent, true);
      options.onStreamEnd?.();

      return accumulatedContent;

    } catch (error: any) {
      console.error('流式请求失败:', error);
      
      if (error.name === 'AbortError') {
        console.log('流式请求被取消');
      } else {
        setError(error);
        options.onError?.(error);
      }
      
      throw error;
    } finally {
      setIsStreaming(false);
      abortControllerRef.current = null;
    }
  }, [parseStreamChunk, options]);

  // 取消流式请求
  const cancelStream = useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
  }, []);

  // 重置状态
  const resetStream = useCallback(() => {
    setStreamContent('');
    setError(null);
    setIsStreaming(false);
  }, []);

  return {
    isStreaming,
    streamContent,
    error,
    sendStreamMessage,
    cancelStream,
    resetStream,
  };
}; 